package com.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.LoginLog;
import com.service.LoginLogService;
import com.utils.PageUtils;
import com.utils.R;

/**
 * 登录日志控制器
 */
@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    private LoginLogService loginLogService;

    /**
     * 分页查询
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params) {
        try {
            // 获取分页参数，设置默认值
            Integer page = 1;
            Integer limit = 10;
            
            if (params.get("page") != null) {
                page = Integer.parseInt(params.get("page").toString());
            }
            if (params.get("limit") != null) {
                limit = Integer.parseInt(params.get("limit").toString());
            }
            
            // 构建查询条件
            EntityWrapper<LoginLog> wrapper = new EntityWrapper<>();
            
            // 添加用户名查询条件
            if (params.get("username") != null) {
                String username = params.get("username").toString();
                if (!username.isEmpty()) {
                    wrapper.like("username", username);
                }
            }
            
            // 添加IP地址查询条件
            if (params.get("ipAddress") != null) {
                String ipAddress = params.get("ipAddress").toString();
                if (!ipAddress.isEmpty()) {
                    wrapper.like("ip_address", ipAddress);
                }
            }
            
            // 添加时间范围查询条件
            if (params.get("dateRange") != null) {
                Object dateRangeObj = params.get("dateRange");
                if (dateRangeObj instanceof String[]) {
                    String[] dateRange = (String[]) dateRangeObj;
                    if (dateRange.length == 2) {
                        wrapper.between("login_time", dateRange[0], dateRange[1]);
                    }
                }
            }
            
            // 按登录时间倒序排序
            wrapper.orderBy("login_time", false);
            
            // 执行分页查询
            Page<LoginLog> pageResult = loginLogService.selectPage(
                new Page<>(page, limit),
                wrapper
            );
            
            return R.ok().put("data", new PageUtils(pageResult));
        } catch (Exception e) {
            return R.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        try {
            LoginLog log = loginLogService.selectById(id);
            if (log == null) {
                return R.error("未找到该记录");
            }
            return R.ok().put("data", log);
        } catch (Exception e) {
            return R.error("获取详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增
     */
    @RequestMapping("/add")
    public R add(@RequestBody LoginLog log) {
        try {
            // 设置创建时间
            log.setLoginTime(new Date());
            loginLogService.insert(log);
            return R.ok();
        } catch (Exception e) {
            return R.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody LoginLog log) {
        try {
            loginLogService.updateById(log);
            return R.ok();
        } catch (Exception e) {
            return R.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id) {
        try {
            loginLogService.deleteById(id);
            return R.ok();
        } catch (Exception e) {
            return R.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatch")
    public R deleteBatch(@RequestBody Long[] ids) {
        try {
            loginLogService.deleteBatchIds(Arrays.asList(ids));
            return R.ok();
        } catch (Exception e) {
            return R.error("批量删除失败：" + e.getMessage());
        }
    }
} 